package org.alma.binary

/**
@author jacob
*/
object Program
{
  def main(args: Array[String]) : Unit =
  {
    val db = Converter.decimalToHex(255)
    
    println(db)
  }
}

/**
@author jacob
*/
object Converter
{
  def hexToDecimal(hex: String) : Int =
  { 
    (for ((value, index) <- hex.toLowerCase.reverse.toArray.map(_.asDigit).zipWithIndex)
       yield value * (Math.pow(16, index).toInt))
    .reduceLeft[Int](_ + _)
  }
  
  def hexToBinary(hex: String) = decimalToBinary(hexToDecimal(hex))

  def decimalToBinary(decimal: Int) : String =
  { 
    var deci = decimal
    val sb = new StringBuilder
    
    do
    {
      val rest = deci % 2
      deci /= 2
      sb.append(rest)
      
    } while (deci > 0)
    
    sb.toString.reverse
  }
  
  private val hexValues = Array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F')
  
  /* way too imperative, i know ...*/
  def decimalToHex(decimal: Int) : String =
  {
    var deci = decimal
    var hex = ""
    
    while (deci > 0)
    {
      hex = hexValues(deci % 16) + hex
      deci /= 16
    }
    
    hex
  }
  
  def binaryToDecimal(binary: String) : Int =
  {
    (for ((value, index) <- binary.reverse.toArray.zipWithIndex) 
       yield value.asDigit * Math.pow(2, index).toInt)
    .reduceLeft[Int](_ + _)
  }
  
  def binaryToHex(binary: String) = decimalToHex(binaryToDecimal(binary))
}

